package at.sternwerk.domainfinder.data.xmlrpc.types;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MapElement extends Element {
  private static final long serialVersionUID = 5418644327118907668L;
  private Map<String, Element> map;

  public MapElement() {
  }

  public MapElement(Map<?, ?> map) {
    this.map = new HashMap<String, Element>();

    for (Object key : map.keySet()) {
      Object o = map.get(key);

      if (o instanceof HashMap<?, ?>) {
        this.map.put((String) key, new MapElement((HashMap<?, ?>) o));
      } else if (o instanceof String) {
        this.map.put((String) key, new StringElement((String) o));
      } else if (o instanceof Integer) {
        this.map.put((String) key, new IntegerElement((Integer) o));
      } else if (o.getClass().isArray()) {
        this.map.put((String) key, new ArrayElement((Object[]) o));
      } else if (o instanceof Double) {
        this.map.put((String) key, new DoubleElement((Double) o));
      }
    }
  }

  public Element get(String key) {
    return map.get(key);
  }

  public Set<String> keySet() {
    return map.keySet();
  }

  public Map<String, Element> getMap() {
    return map;
  }

  @Override
  public String toString() {
    String result = "{\n";

    for (String key : keySet()) {
      result += "    " + key + " : " + get(key).toString() + " \n";
    }

    result += "}\n";

    return result;
  }

  @Override
  public List<Element> getChildren() {
    List<Element> result = new ArrayList<Element>();

    for (Element elem : map.values()) {
      result.addAll(elem.getChildren());
      result.add(elem);
    }

    return result;
  }
}
